package com.vanysoft.framework.config.database;

import com.baomidou.mybatisplus.mapper.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;

import java.time.LocalDateTime;

/**
 * @author qi_ma
 * @version 1.0 2017/11/23 17:30
 */
public class CurrentMetaObjectHandler extends MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {
        Object createUser = getFieldValByName("createUser", metaObject);
        Object createTime = getFieldValByName("createTime", metaObject);
//        UserInfo userInfo;
//        try {
//            userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        } catch (NullPointerException | ClassCastException e1) {
//            userInfo = null;
//        }
//        if (createUser == null && metaObject.hasGetter("createUser")) {
//            setFieldValByName("createUser", userInfo != null ? userInfo.getUserName() : "", metaObject);
//        }
        if (createTime == null && metaObject.hasGetter("createTime")) {
            setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        Object modifyUser = getFieldValByName("modifyUser", metaObject);
        Object modifyTime = getFieldValByName("modifyTime", metaObject);
//        UserInfo userInfo;
//        try {
//            userInfo = (UserInfo) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
//        } catch (NullPointerException e) {
//            userInfo = null;
//        }
//        if (modifyUser == null && metaObject.hasGetter("modifyUser")) {
//            setFieldValByName("modifyUser", userInfo != null ? userInfo.getUserName() : "", metaObject);
//        }
        if (modifyTime == null && metaObject.hasGetter("modifyTime")) {
            setFieldValByName("modifyTime", LocalDateTime.now(), metaObject);
        }
    }
}